package com.cheetah.start.system.back.controller;

import com.cheetah.start.common.base.result.Result;
import com.cheetah.start.common.base.result.ResultController;
import com.cheetah.start.common.base.result.ResultTable;
import com.cheetah.start.common.config.property.UpLoadProprety;
import com.cheetah.start.common.enums.BusinessType;
import com.cheetah.start.common.query.PageQuery;
import com.cheetah.start.common.utils.MySystemUtil;
import com.cheetah.start.common.utils.MyZipUtil;
import com.cheetah.start.system.back.domain.Back;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 备份 不打算用这个了 这个应该由一个单独的程序来管
 *
 * @author Feel
 * @date 2021/08/08
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/back")
public class BackController extends ResultController {

    @Autowired
    private UpLoadProprety upLoadProprety;

    /**
     * 列表
     *
     * @param pageQuery 页面查询
     * @return {@link ResultTable}
     */
    @GetMapping("/list")
    public ResultTable list(PageQuery pageQuery) {
        File file = new File(upLoadProprety.getBack());
        if (!file.exists()) {
            file.mkdirs();
            return pageTable(null, 0);
        }
        File[] files = file.listFiles();
        List<Back> backs = new ArrayList<>();
        for (File file1 : files) {
            Back back = new Back();
            back.setFileName(file1.getName());
            back.setFileSize(file1.length() / 1024);
            backs.add(back);
        }
        return pageTable(backs, backs.size());
    }


    /**
     * 备份
     *
     * @return {@link Result}
     */
    @PostMapping("/back")
    public Result back() throws IOException {
        if (MySystemUtil.isWin()) {
            File f = new File(upLoadProprety.getBack());
            if (!f.exists()) {
                boolean mkdirs = f.mkdirs();
                log.info("创建文件夹是否成功:[{}]", mkdirs);
            }
            Runtime.getRuntime().exec(upLoadProprety.getPath() + "back-win.bat");
            return success("请查看文件");
        } else {
            return failure("目前只支持 win 系统备份");
        }
    }


    /**
     * 检查文件是否存在
     *
     * @param fileName 文件名称
     * @return {@link Result}
     */
    @GetMapping("/check")
    public Result check(@NotBlank(message = "文件名不能为空") String fileName) {
        File file = new File(upLoadProprety.getBack() + fileName);
        return decide(file.exists(), "文件可以下载", "文件不存在");
    }

    /**
     * 下载
     *
     * @param fileName 文件名称
     * @param response 响应
     * @param request  请求
     */
    @GetMapping("/download")
    public void downLoad(@NotBlank(message = "文件名不能为空") String fileName, HttpServletResponse response, HttpServletRequest request) {
        File fileurl = new File(upLoadProprety.getBack() + fileName);
        try {
            //将文件读入文件流
            InputStream inStream = new FileInputStream(fileurl);
            //获得浏览器代理信息
            final String userAgent = request.getHeader("USER-AGENT");
            //判断浏览器代理并分别设置响应给浏览器的编码格式
            String finalFileName = null;
            if (StringUtils.contains(userAgent, "MSIE") || StringUtils.contains(userAgent, "Trident")) {
                //IE浏览器
                finalFileName = URLEncoder.encode(fileName, "UTF8");
            } else if (StringUtils.contains(userAgent, "Mozilla")) {
                //google,火狐浏览器
                finalFileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                //其他浏览器
                finalFileName = URLEncoder.encode(fileName, "UTF8");
            }
            //设置HTTP响应头
            //重置 响应头
            response.reset();
            response.setContentType("text/x-sql");
            response.addHeader("Content-Disposition", "attachment;filename=\"" + finalFileName + "\"");
            // 循环取出流中的数据
            byte[] b = new byte[1024];
            int len;
            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
            response.getOutputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 下载文件夹
     *
     * @param response 响应
     */
    @GetMapping("/downloads")
    public void downloads(HttpServletResponse response) {
        File file = new File(upLoadProprety.getBack());
        if (!file.exists()) {
            file.mkdirs();
        }
        MyZipUtil.zip(upLoadProprety.getBack(), response);
    }

    /**
     * 删除
     *
     * @param fileName 文件名称
     * @return {@link Result}
     */
    @PostMapping("/delete")
    public Result delete(@NotBlank(message = "文件名不能为空") String fileName) {
        File file = new File(upLoadProprety.getBack() + fileName);
        if (file.exists()) {
            boolean delete = file.delete();
            return decide(delete, BusinessType.REMOVE);
        }
        return success("文件不存在或已被删除");
    }
}
